const CheckupService = require('../services/checkup.service');
const { validationResult } = require('express-validator');

class CheckupController {
  /**
   * 创建体检记录
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async createCheckup(req, res) {
    try {
      // 验证请求数据
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        console.log('验证失败的数据:', JSON.stringify(req.body, null, 2));
        console.log('验证错误:', errors.array());
        return res.status(400).json({
          success: false,
          message: '数据验证失败',
          errors: errors.array()
        });
      }
      
      const checkupData = req.body;
      const result = await CheckupService.createCheckup(checkupData);
      
      res.status(201).json(result);
    } catch (error) {
      console.error('创建体检记录失败:', error);
      res.status(500).json({
        success: false,
        message: '创建体检记录失败',
        error: error.message
      });
    }
  }
  
  /**
   * 获取体检记录详情
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async getCheckup(req, res) {
    try {
      const { id } = req.params;
      
      if (!id || isNaN(id)) {
        return res.status(400).json({
          success: false,
          message: '无效的体检记录ID'
        });
      }
      
      const result = await CheckupService.getCompleteCheckup(parseInt(id));
      
      res.json(result);
    } catch (error) {
      console.error('获取体检记录失败:', error);
      
      if (error.message === '体检记录不存在') {
        return res.status(404).json({
          success: false,
          message: error.message
        });
      }
      
      res.status(500).json({
        success: false,
        message: '获取体检记录失败',
        error: error.message
      });
    }
  }
  
  /**
   * 更新体检记录
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async updateCheckup(req, res) {
    try {
      const { id } = req.params;
      const updateData = req.body;
      
      if (!id || isNaN(id)) {
        return res.status(400).json({
          success: false,
          message: '无效的体检记录ID'
        });
      }
      
      // 验证请求数据
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '数据验证失败',
          errors: errors.array()
        });
      }
      
      const result = await CheckupService.updateCheckup(parseInt(id), updateData);
      
      res.json(result);
    } catch (error) {
      console.error('更新体检记录失败:', error);
      res.status(500).json({
        success: false,
        message: '更新体检记录失败',
        error: error.message
      });
    }
  }
  
  /**
   * 删除体检记录
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async deleteCheckup(req, res) {
    try {
      const { id } = req.params;
      
      if (!id || isNaN(id)) {
        return res.status(400).json({
          success: false,
          message: '无效的体检记录ID'
        });
      }
      
      const result = await CheckupService.deleteCheckup(parseInt(id));
      
      res.json(result);
    } catch (error) {
      console.error('删除体检记录失败:', error);
      res.status(500).json({
        success: false,
        message: '删除体检记录失败',
        error: error.message
      });
    }
  }
  
  /**
   * 获取体检记录列表
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async getCheckupList(req, res) {
    try {
      const {
        page = 1,
        limit = 10,
        daId,
        startDate,
        endDate,
        xm,
        sfzh,
        tjzt
      } = req.query;
      
      const params = {
        page: parseInt(page),
        limit: parseInt(limit)
      };
      
      // 添加筛选条件
      if (daId) params.daId = daId;
      if (startDate) params.startDate = startDate;
      if (endDate) params.endDate = endDate;
      if (xm) params.xm = xm;
      if (sfzh) params.sfzh = sfzh;
      if (tjzt) params.tjzt = tjzt;
      
      const result = await CheckupService.getCheckupList(params);
      
      res.json(result);
    } catch (error) {
      console.error('获取体检记录列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取体检记录列表失败',
        error: error.message
      });
    }
  }
  
  /**
   * 获取体检统计信息
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async getCheckupStats(req, res) {
    try {
      const { daId, startDate, endDate } = req.query;
      
      const params = {};
      if (daId) params.daId = daId;
      if (startDate) params.startDate = startDate;
      if (endDate) params.endDate = endDate;
      
      const result = await CheckupService.getCheckupStats(params);
      
      res.json(result);
    } catch (error) {
      console.error('获取体检统计信息失败:', error);
      res.status(500).json({
        success: false,
        message: '获取体检统计信息失败',
        error: error.message
      });
    }
  }
  
  /**
   * 根据档案ID获取体检记录
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async getCheckupByDaId(req, res) {
    try {
      const { daId } = req.params;
      
      if (!daId) {
        return res.status(400).json({
          success: false,
          message: '档案ID不能为空'
        });
      }
      
      const params = {
        daId,
        page: 1,
        limit: 100 // 获取该档案的所有体检记录
      };
      
      const result = await CheckupService.getCheckupList(params);
      
      res.json(result);
    } catch (error) {
      console.error('根据档案ID获取体检记录失败:', error);
      res.status(500).json({
        success: false,
        message: '获取体检记录失败',
        error: error.message
      });
    }
  }
  
  /**
   * 批量删除体检记录
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  static async batchDeleteCheckups(req, res) {
    try {
      const { ids } = req.body;
      
      if (!ids || !Array.isArray(ids) || ids.length === 0) {
        return res.status(400).json({
          success: false,
          message: '请提供要删除的体检记录ID数组'
        });
      }
      
      const results = [];
      const errors = [];
      
      for (const id of ids) {
        try {
          const result = await CheckupService.deleteCheckup(parseInt(id));
          results.push({ id, success: true });
        } catch (error) {
          errors.push({ id, error: error.message });
        }
      }
      
      res.json({
        success: true,
        message: `成功删除 ${results.length} 条记录`,
        data: {
          successful: results,
          failed: errors
        }
      });
    } catch (error) {
      console.error('批量删除体检记录失败:', error);
      res.status(500).json({
        success: false,
        message: '批量删除体检记录失败',
        error: error.message
      });
    }
  }
}

module.exports = CheckupController;